<template>
  <div id="users">
    <div class="card">
      <div class="card-body">
        <form class="row row-cols-lg-auto align-items-center">
          <div class="col-1">
            <input
              type="textfield"
              class="form-control"
              placeholder="用户名"
              v-model.trim="username"
              size="10"
            />
          </div>
          <div class="col-1 ms-1">
            <input
              type="textfield"
              class="form-control"
              placeholder="手机"
              v-model.trim="mobile"
              size="10"
            />
          </div>
          <div class="col-1 ms-1">
            <input
              type="textfield"
              class="form-control"
              placeholder="eterm用户名"
              v-model.trim="etermUsername"
              size="10"
            />
          </div>
          状态
          <div class="col-1 ms-1">
            <select class="form-select" v-model.number="status">
              <option value="-1">全部</option>
              <option value="0">未启用</option>
              <option value="1">正常</option>
              <option value="4">停用</option>
            </select>
          </div>
          <div class="col-1 ms-1">
            <select class="form-select" v-model.number="sc.pageSize">
              <option value="25">25</option>
              <option value="50">50</option>
              <option value="100">100</option>
              <option value="500">500</option>
            </select>
          </div>
          <div class="col">
            <button
              type="button"
              class="btn btn-primary ms-1"
              @click.stop="search()"
            >
              查找
            </button>
            <button
              type="button"
              class="btn btn-secondary ms-1"
              @click.stop="reset()"
            >
              重置
            </button>

            <button
              type="button"
              v-on:click="newUser()"
              class="btn btn-success ms-5 float-end"
            >
              新建
            </button>
          </div>
        </form>
      </div>
      <table class="table table-striped table-hover table-sm">
        <thead>
          <tr>
            <th>用户名</th>
            <th>全名</th>
            <th>手机</th>
            <th>邮件</th>
            <th>部门</th>
            <th>企业微信id</th>
            <th>eterm用户名</th>
            <th>状态</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(user, index) in userList"
            :key="user.username"
          >
            <td>{{ user.username }}</td>
            <td>{{ user.empname }}</td>
            <td>{{ user.mobileNo }}</td>
            <td>{{ user.email }}</td>
            <td>
              <template v-for="info in user.departments">
                {{ info.name }},
              </template>
            </td>
            <td>
              {{ user.wwUserId }}
              <span v-if="user.wwUserId.length > 0">
                <img :src="user.avatar" width="25" height="25" />
                <a
                  href="javascript:void(0)"
                  v-on:click="delWwUser(index)"
                  class="text-danger"
                  >删除</a
                >
                <a href="javascript:void(0)" v-on:click="syncWwUser(index)"
                  >同步</a
                >
              </span>
            </td>
            <td>
              <template v-if="user.etermUsername !== null">
                <template v-if="user.etermUsername.length > 10">
                  <span :title="user.etermUsername"
                    >{{ user.etermUsername.substring(0, 10) }}...</span
                  >
                </template>
                <template v-else>
                  {{ user.etermUsername }}
                </template>
              </template>
            </td>
            <td>
              <span v-if="user.status === 1">正常</span>
              <span v-if="user.status === 4">停用</span>
            </td>
            <td>
              <a
                href="javascript:void(0)"
                @click.stop="editUser(index)"
                class=""
                >修改</a
              >
              <a
                href="javascript:void(0)"
                @click.stop="resetPassword(index)"
                class="ms-2 text-danger"
                v-if="isAdmin"
                >重置密码</a
              >
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <nav id="pagination-box" class="float-end">
      <my-pagination
        name="pagination"
        :row-count="sc.rowCount"
        :page-total="sc.pageTotal"
        :page-no="sc.pageNo"
        @next-page="nextPage"
        @prev-page="prevPage"
        @direct-page="directPage"
      ></my-pagination>
    </nav>

    <my-modal-prompt ref="modalPrompt">
      <span slot="title">{{ modalTitle }}</span>
    </my-modal-prompt>
    <my-modal-user ref="modalUser" :departments="departments"></my-modal-user>
  </div>
</template>

<script>
import $ from "jquery";
import { mapActions } from "vuex";
import {
  searchUsers,
  createUser,
  searchDepartments,
  deleteWwUser,
  syncWwUser,
  resetUserPassword,
} from "@/api/admin.js";
import MyPagination from "@/components/my-pagination.vue";
import MyModalPrompt from "@/components/modal/my-modal-prompt.vue";
import MyModalUser from "@/components/modal/my-modal-user.vue";

export default {
  components: {
    MyPagination,
    MyModalPrompt,
    MyModalUser,
  },
  data() {
    return {
      modalTitle: "",
      sc: {
        rowCount: 0,
        pageNo: 1,
        pageSize: 25,
        pageTotal: 0,
      },
      username: "",
      mobile: "",
      etermUsername: "",
      status: -1,

      userList: [],
      user: {
        id: 0,
        username: "",
        empname: "",
        mobileNo: "",
        email: "",
        etermUsername: "",
        position: "",
        status: 0,
      },
      deptIds: [],
      departments: [],
      syncWxWork: 1,
    };
  },
  computed: {
    isAdmin() {
      return this.$store.getters.isAdmin;
    },
  },
  mounted: function () {
    if (window.matchMedia("(max-width: 576px)").matches) {
      // console.log(this.$router.to)
      this.$router.replace("/h5/admin/users");
    } else {
      this.search();
      this.searchDepartments();
    }
  },
  methods: {
    ...mapActions(["showLoading", "hideLoading"]),
    showErrMsg: function (msg, msgType) {
      this.$store.dispatch("showAlertMsg", {
        errMsg: msg,
        errMsgType: msgType,
      });
    },
    search: function () {
      this.showLoading();

      const params = {
        "sc.pageNo": this.sc.pageNo,
        "sc.pageSize": this.sc.pageSize,
        "sc.username": this.username,
        "sc.mobile": this.mobile,
        "sc.etermUsername": this.etermUsername,
        "sc.status": this.status,
      };

      searchUsers(
        params,
        (v) => {
          this.userList = v.dataList;
          this.sc = v.page;
        },
        () => this.hideLoading()
      );
    },
    newUser: function () {
      this.user.id = 0;
      this.user.username = "";
      this.user.empname = "";
      this.user.mobileNo = "";
      this.user.email = "";
      this.user.etermUsername = "";
      this.user.position = "";
      this.user.status = 1;

      this.deptIds.splice(0);

      this.$refs.modalUser
        .modal(this.user, this.deptIds)
        .then((v) => {
          this.createUser(v);
        })
        .catch((ex) => {});
    },
    createUser: function (v) {
      const params = {
        id: this.user.id,
        username: this.user.username,
        fullName: this.user.empname,
        mobileNo: this.user.mobileNo,
        email: this.user.email,
        position: this.user.position,
        etermUsername: this.user.etermUsername,
        status: this.user.status,
        departments: this.deptIds,
        syncWxWork: this.syncWxWork,
      };

      createUser(params, (jsonResult) => {
        if (jsonResult.status !== "OK") {
          this.showErrMsg(jsonResult.errmsg);
        } else {
          this.showErrMsg("操作完成");
          this.search();
        }
      });
    },
    editUser: function (index) {
      const info = this.userList[index];
      this.user.id = info.id;
      this.user.username = info.username;
      this.user.empname = info.empname;
      this.user.mobileNo = info.mobileNo;
      this.user.email = info.email;
      this.user.etermUsername = info.etermUsername;
      this.user.status = info.status;
      this.user.position = info.position;

      this.deptIds.splice(0);
      if (info.departments !== null) {
        for (const d of info.departments) {
          this.deptIds.push(d.id);
        }
      }

      this.$refs.modalUser
        .modal(this.user, this.deptIds)
        .then((v) => {
          this.deptIds = v.deptIds;
          this.createUser(v);
        })
        .catch((ex) => {});
    },
    searchDepartments: function () {
      const params = {
        "sc.pageNo": 1,
        "sc.pageSize": 500,
      };

      searchDepartments(params, (jsonResult) => {
        this.departments = jsonResult.dataList;
      });
    },
    delWwUser: function (index) {
      const info = this.userList[index];

      this.modalTitle = "确定从企业微信中删除该用户吗？";

      this.$refs.modalPrompt
        .modal()
        .then((remark) => {
          this.showLoading();
          const params = {
            id: info.id,
            remark: remark,
          };
          deleteWwUser(
            params,
            (v) => {
              if (v.status !== "OK") {
                this.showErrMsg(v.errmsg, "danger");
              } else {
                this.showErrMsg(v.desc);
                this.search();
              }
            },
            () => {
              this.hideLoading();
            }
          );
        })
        .catch((ex) => {});
    },
    syncWwUser: function (index) {
      const info = this.userList[index];
      const params = {
        id: info.id,
      };

      syncWwUser(
        params,
        (v) => {
          if (v.status !== "OK") {
            this.showErrMsg(v.errmsg, "danger");
          } else {
            this.showErrMsg(v.desc);
            this.search();
          }
        },
        () => {
          this.hideLoading();
        }
      );
    },
    resetPassword: function (index) {
      const info = this.userList[index];

      this.modalTitle = "重置用户(" + info.username + ")密码, 请输入新密码";

      this.$refs.modalPrompt
        .modal()
        .then((remark) => {
          this.showLoading();

          const params = {
            id: info.id,
            password: remark,
          };
          resetUserPassword(
            params,
            (v) => {
              if (v.status !== "OK") {
                this.showErrMsg(v.errmsg, "danger");
              } else {
                this.showErrMsg("操作成功");
                // this.search()
              }
            },
            () => {
              this.hideLoading();
            }
          );
        })
        .catch((ex) => {});
    },
    reset: function () {
      this.username = "";
      this.mobile = "";
      this.etermUsername = "";
    },
    prevPage: function () {
      this.sc.pageNo = this.sc.pageNo - 1;
      if (this.sc.pageNo < 1) this.sc.pageNo = 1;
      this.search();
    },
    nextPage: function () {
      this.sc.pageNo = this.sc.pageNo + 1;
      this.search();
    },
    directPage: function (pageNo) {
      this.sc.pageNo = pageNo;
      this.search();
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 通过 `vm` 访问组件实例
      console.log(to);
      console.log(from);
      console.log(vm);
    });
  },
};
</script>
